package sevelet;

import com.alibaba.fastjson.JSONObject;
import utils.VerifyCodeUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "VerifyCodeServlet", value = "/verifyCode")
public class VerifyCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        switch (method){
            case "getCode":
                getCode(request,response);
                break;
            case "checkCode":
                checkCode(request,response);
                break;
        }
    }
    private void getCode(HttpServletRequest request, HttpServletResponse
            response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        String verifyCode = VerifyCodeUtil.outputVerifyImage(100, 40,
                outputStream, 4);
//将验证码存入Session对象
        HttpSession session = request.getSession();
        session.setAttribute("VERIFY_CODE",verifyCode);
    }
    private void checkCode(HttpServletRequest request, HttpServletResponse
            response) throws IOException {
        HttpSession session = request.getSession();
        String verifyCodeInSession = (String)
                session.getAttribute("VERIFY_CODE");
        String verify = request.getParameter("verify");
        Map<String,String> resultMap = new HashMap();
        if(verifyCodeInSession!=null && verifyCodeInSession.equals(verify)){
            resultMap.put("result", "VERIFY_PASS");
        }else{
            resultMap.put("result", "VERIFY_FAIL");
        }
        Object o = JSONObject.toJSON(resultMap);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(o);
    }



    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);

    }
}
